package com.j4dream.property.web.common;

import com.j4dream.property.web.exception.DuplicateResourceException;
import com.j4dream.property.web.exception.ResourceNotFoundException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@ControllerAdvice
public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity unkonwExcepiton(Exception ex) {
        return ResponseEntity.status(HttpStatus.BAD_GATEWAY).body(new ExceptionResBody(ex.getMessage()));
    }

    @ExceptionHandler(value = ResourceNotFoundException.class)
    public ResponseEntity resourceNotFoundHandler(ResourceNotFoundException ex) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ExceptionResBody(ex.getMessage()));
    }

    @ExceptionHandler(value = DuplicateResourceException.class)
    public ResponseEntity duplicateResourceHandler(DuplicateResourceException ex) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ExceptionResBody(ex.getMessage()));
    }


    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        //return super.handleMethodArgumentNotValid(ex, headers, status, request);
        BindingResult bindingResult = ex.getBindingResult();
        String error;
        if (bindingResult != null && bindingResult.hasErrors()) {
            error = bindingResult.getFieldErrors()
                    .stream().map(e -> e.getField() + " " + e.getDefaultMessage())
                    .collect(Collectors.joining(","));
        } else {
           error = ex.getMessage();
        }
        Map rs = new HashMap();
        rs.put("error", error);
        return ResponseEntity.badRequest().body(rs);
    }
}